package com.fh.modules.dbms.controller;

import com.alibaba.fastjson.JSON;
import com.autocode.codegenerate.FreeMarkerAutoCodeUtil;
import com.fh.common.api.vo.Result;
import com.fh.common.aspect.annotation.AutoLog;
import com.fh.common.constant.CommonConstant;
import com.fh.common.util.StringUtils;
import com.fh.db.SqlColumn;
import com.fh.db.SqlRunner;
import com.fh.modules.dbms.service.IDbmsDbsourceService;
import com.fh.modules.dbms.vo.AutoCodeSqlVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author qiujunda
 * @Date 18/05/2020
 * @Description
 */
@RestController
@RequestMapping("/dbms/autoCode")
@Slf4j
public class DbmsAutoCodeController {

    @Autowired
    private IDbmsDbsourceService dbmsDbsourceService;

    @PostMapping(value = "/querySqlColumns")
    @ApiOperation("查询sql的结果列信息")
    @AutoLog(value = "查询sql的结果列信息", logType = CommonConstant.LOG_TYPE_QUERY)
    public Result querySqlColumns(@RequestBody AutoCodeSqlVo autoCodeSqlVo) throws Exception {
        if (autoCodeSqlVo.getDbsource() == null || autoCodeSqlVo.getSql() == null) {
            return Result.ok("");
        }
        return Result.ok(SqlRunner.querySqlColumns(dbmsDbsourceService.getDbSource(autoCodeSqlVo.getDbsource()), autoCodeSqlVo.getSql()));
    }

    @PostMapping(value = "/querySqlData")
    @ApiOperation("查询sql的结果信息")
    @AutoLog(value = "查询sql的结果信息", logType = CommonConstant.LOG_TYPE_QUERY)
    public Result querySqlData(@RequestBody AutoCodeSqlVo autoCodeSqlVo) throws Exception {
        if (autoCodeSqlVo.getDbsource() == null || autoCodeSqlVo.getSql() == null) {
            return Result.ok("");
        }
        return Result.ok(SqlRunner.querySqlData(dbmsDbsourceService.getDbSource(autoCodeSqlVo.getDbsource()), autoCodeSqlVo.getSql(),0,20));
    }

    @PostMapping(value = "/generateCode")
    @ApiOperation("自动生成代码")
    @AutoLog(value = "自动生成代码", logType = CommonConstant.LOG_TYPE_ACTION)
    public Result generateCode(@RequestBody AutoCodeSqlVo autoCodeSqlVo) {
        String templatePath = FreeMarkerAutoCodeUtil.class.getResource("/code_generate/template/fherp").getFile();
        Map hashMap = new HashMap();
        List<SqlColumn> sqlColumnList = autoCodeSqlVo.getSqlColumnList().stream().
                sorted(Comparator.comparing(SqlColumn::getRowNumber)).
                collect(Collectors.toList());
        autoCodeSqlVo.setSqlColumnList(sqlColumnList);
        hashMap.put("paramsList", autoCodeSqlVo.getSqlColumnList().stream().
                filter(sqlColumn -> !"none".equals(sqlColumn.getQueryParamType())).
                sorted(Comparator.comparing(SqlColumn::getRowNumber)).
                collect(Collectors.toList()));
        String sumColumns="",countColumns="";
        for(int i=0;i<autoCodeSqlVo.getSqlColumnList().size();i++){
            SqlColumn sqlColumn=autoCodeSqlVo.getSqlColumnList().get(i);
            sumColumns+=(sqlColumn.getColumnName()+",");
            countColumns+=(sqlColumn.getColumnName()+",");
        }
        if(sumColumns.length()>0){
            sumColumns=sumColumns.substring(0,sumColumns.length()-1);
        }
        if(countColumns.length()>0){
            countColumns=countColumns.substring(0,countColumns.length()-1);
        }
        autoCodeSqlVo.setSumColumns(sumColumns);
        autoCodeSqlVo.setCountColumns(countColumns);
        hashMap.putAll( (Map<String, Object>) JSON.toJSON(autoCodeSqlVo));
        FreeMarkerAutoCodeUtil.autoGenerateCodeFile(templatePath, hashMap,
                "fherp-html.ftl", StringUtils.lowerFirst(autoCodeSqlVo.getSystemCode()) + ".html");
        FreeMarkerAutoCodeUtil.autoGenerateCodeFile(templatePath, hashMap,
                "fherp-js.ftl", StringUtils.lowerFirst(autoCodeSqlVo.getSystemCode())  + ".js");
        FreeMarkerAutoCodeUtil.autoGenerateCodeFile(templatePath, hashMap,
                "fherp-java.ftl", StringUtils.lowerFirst(autoCodeSqlVo.getSystemCode())  + ".txt");
        return Result.ok("生成代码成功");
    }
}
